package com.example.wacoffee_manage.Service.Impl;

import com.example.wacoffee_manage.Mapper.UserMapper;
import com.example.wacoffee_manage.Service.userService;
import com.example.wacoffee_manage.common.PageResult;
import com.example.wacoffee_manage.pojo.User;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class userServiceImpl implements userService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public com.example.wacoffee_manage.common.PageResult getAllUsers(User user) {
        PageHelper.startPage(user.getPage(),user.getPageSize());
        List<User> users = userMapper.getAllUsers(user);
        Page<User> page = (Page<User>) users;
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(User user) {
        userMapper.add(user);
    }

    @Override
    public User getById(int id) {
        return userMapper.getById(id);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void delete(int id) {
    userMapper.delete(id);
    }

    @Override
    public void recover(int id) {
        userMapper.recover(id);
    }

    @Override
    public void importUserData(MultipartFile file) throws IOException {
        List<User> users = new ArrayList<>();

        // 使用 try-with-resources 确保资源自动关闭
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0);

            // 从第1行(index=1)开始，跳过表头
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue; // 跳过空行
                }

                User user = new User();

                // 处理用户名
                Cell usernameCell = row.getCell(0);
                if (usernameCell == null || StringUtil.isBlank(getCellValueAsString(usernameCell))) {
                    throw new RuntimeException("第" + (i + 1) + "行用户名不能为空");
                }
                user.setUserName(getCellValueAsString(usernameCell).trim());

                // 处理密码
                Cell passwordCell = row.getCell(1);
                if (passwordCell == null || StringUtil.isBlank(getCellValueAsString(passwordCell))) {
                    throw new RuntimeException("第" + (i + 1) + "行密码不能为空");
                }
                user.setPassword(getCellValueAsString(passwordCell).trim());

                // 处理性别
                Cell genderCell = row.getCell(2);
                if (genderCell == null) {
                    throw new RuntimeException("第" + (i + 1) + "行性别不能为空");
                }
                int gender = (int) genderCell.getNumericCellValue();
                if (gender != 1 && gender != 2) {
                    throw new RuntimeException("第" + (i + 1) + "行性别只能为1(男)或2(女)");
                }
                user.setGender(gender);

                // 处理手机号
                Cell phoneCell = row.getCell(3);
                if (phoneCell == null || StringUtil.isBlank(getCellValueAsString(phoneCell))) {
                    throw new RuntimeException("第" + (i + 1) + "行手机号不能为空");
                }
                String phone = getCellValueAsString(phoneCell).trim();
                if (!phone.matches("^1[3-9]\\d{9}$")) { // 手机号应为11位数字
                    throw new RuntimeException("第" + (i + 1) + "行手机号格式错误");
                }
                user.setPhone(phone);

                // 处理头像
                Cell imageCell = row.getCell(4);
                if (imageCell != null && !StringUtil.isBlank(getCellValueAsString(imageCell))) {
                    user.setImage(getCellValueAsString(imageCell).trim());
                }

                // 处理余额（可选字段）
                Cell balanceCell = row.getCell(5);
                if (balanceCell != null && balanceCell.getCellType() != CellType.BLANK) {
                    double balance = balanceCell.getNumericCellValue();
                    if (balance < 0) {
                        throw new RuntimeException("第" + (i + 1) + "行余额不能小于0");
                    }
                    user.setBalance(balance);
                }

                users.add(user);
            }
        }

        // 批量插入用户数据
        if (!users.isEmpty()) {
            userMapper.importUserData(users);
        }
    }
    // 辅助方法：安全获取单元格字符串值
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return null;
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf((long) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }
}
